var uploadForm = $("#uploadForm");
var currentPath = "";

// 监听 hashchange 事件，当 URL 的 hash 发生变化时加载对应的文件列表
window.addEventListener("hashchange", function () {
  var hashPath = window.location.hash.slice(1);
  loadFiles(hashPath);
});

$(document).ready(function () {
  var initialHash = window.location.hash.slice(1);
  loadFiles(initialHash);
});

// 定义显示消息的函数
function showMessage(message, type) {
  if (!type) {
    type = "info";
  }
  var messageBar = $("#message-bar");
  // 移除所有消息类型的类
  messageBar.removeClass("info success error warn");
  // 添加当前消息类型的类
  messageBar.addClass(type);
  // 设置消息内容
  messageBar.text(message);
}

// 修改 loadFiles 函数
function loadFiles(path) {
  if (!path) {
    path = "";
  }
  currentPath = path;

  showMessage("正在加载...");

  var url = "/list_directories?path=" + encodeURIComponent(path);
  $.getJSON(url, function (response) {
    if (!response.success) {
      // 显示错误消息
      showMessage(response.message, "error");
      return;
    }

    var items = response.data;

    $("#fileList").empty().append("<ul>");
    var list = $("#fileList").empty();
    var ul = $("<ul>");

    if (items.length === 0) {
      ul.append("<li><span>空目录</span></li>");
    } else {
      var directories = items.filter(function (item) {
        return item.type === "directory";
      });
      var files = items.filter(function (item) {
        return item.type === "file";
      });
      // directories.sort((a, b) => a.name.localeCompare(b.name));
      // files.sort((a, b) => a.name.localeCompare(b.name));
      var sortedItems = [];
      sortedItems = sortedItems.concat(directories);
      sortedItems = sortedItems.concat(files);

      sortedItems.forEach(function (item) {
        item.path = item.path.replace(/\\/g, "/");
        // 调用工具函数
        appendListItem(ul, item, item.name);
      });
    }
    list.append(ul);
    showMessage("加载完成");
    // 更新面包屑和标题
    document.title = "/" + decodeURIComponent(path) + " - " + window.$appName;
    updateBreadcrumb();
  }).fail(function (jqXHR, textStatus, errorThrown) {
    // 显示错误消息
    showMessage("加载数据失败:" + textStatus + " - " + errorThrown, "error");
  });
}

// 修改 searchFiles 函数
function searchFiles() {
  var btn = $("#btn-search");
  var query = $("#query").val();
  if (!query) {
    if (window.location.hash === "#" + currentPath) {
      loadFiles(currentPath);
    } else {
      window.location.hash = currentPath;
    }
    btn.prop("disabled", false);
    return;
  }
  btn.prop("disabled", true);
  var breadcrumb = $("#breadcrumb").empty();
  breadcrumb.append('<a href="#" class="root">根目录</a>');
  breadcrumb.append('<span class="seperator"></span>');

  var searching = $('<span class="searching">搜索中...</span>');
  breadcrumb.append(searching);
  var timeElapsed = $('<span class="time-elapsed"></span>');
  breadcrumb.append(timeElapsed);

  uploadForm.hide();

  var list = $("#fileList").empty();
  var ul = $("<ul>");
  list.append(ul);

  // 提前编译正则表达式
  var cleanQuery = query.trim();
  var hasExtension = cleanQuery.includes(".");
  var kwRegex = null;
  var extRegex = null;
  if (cleanQuery) {
    var keyword = cleanQuery;
    var ext;
    if (hasExtension) {
      var temp = cleanQuery.split(".");
      keyword = temp[0];
      ext = temp[1];
    }
    kwRegex = new RegExp(
      keyword.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"),
      "i"
    );
    if (ext) {
      extRegex = new RegExp(
        "\\." + ext.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") + "$",
        "i"
      );
    }
  }

  // 显示信息消息
  showMessage("正在搜索...", "info");

  // 创建 EventSource 实例
  var eventSource = new EventSource("/search/" + encodeURIComponent(query));
  var total = 0;
  var startTime = new Date().getTime();

  // 自动更新搜索时长
  var updateTimeElapsed = setInterval(function () {
    var elapsed = new Date().getTime() - startTime;
    timeElapsed.text("， 耗时: " + (elapsed / 1000).toFixed(3) + " 秒");
  }, 100);

  eventSource.onmessage = function (event) {
    try {
      var data = JSON.parse(event.data);
      if (data.success) {
        if (data.data.length > 0) {
          data.data.forEach(function (item) {
            item.path = item.path.replace(/\\/g, "/");
            var text = item.name;

            // 使用提前编译好的正则表达式进行高亮
            if (kwRegex) {
              text = text.replace(kwRegex, '<span class="highlight">$&</span>');
            }
            if (extRegex) {
              text = text.replace(
                extRegex,
                '<span class="highlight">$&</span>'
              );
            }

            // 调用工具函数
            appendListItem(ul, item, text, true);
            total++;
            searching.text("搜索中，已找到 " + total + " 个结果");
          });
        } else if (data.message) {
          btn.prop("disabled", false);
          clearInterval(updateTimeElapsed);
          searching.text("搜索完成，共找到 " + total + " 个结果");
          var elapsed = new Date().getTime() - startTime;
          timeElapsed.text("， 耗时: " + (elapsed / 1000).toFixed(3) + " 秒");
          // 根据消息内容判断类型，这里简单假设包含成功字样为 success
          var messageType = data.message.includes("成功") ? "success" : "info";
          showMessage(data.message, messageType);
          eventSource.close();
        }
      } else {
        btn.prop("disabled", false);
        clearInterval(updateTimeElapsed);
        // 显示错误消息
        showMessage(data.message, "error");
        searching.text("搜索出错");
        eventSource.close();
      }
    } catch (error) {
      btn.prop("disabled", false);
      clearInterval(updateTimeElapsed);
      console.error("解析 SSE 数据出错:", error);
      searching.text("搜索出错");
      // 显示错误消息
      showMessage("解析搜索结果出错，请稍后重试", "error");
      eventSource.close();
    }
  };

  eventSource.onerror = function (error) {
    btn.prop("disabled", false);
    clearInterval(updateTimeElapsed);
    console.error("SSE 连接出错:", error);
    // 显示错误消息
    showMessage("搜索失败，请稍后重试", "error");
    eventSource.close();
  };
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (bytes === 0) return "0 Bytes";
  if (!bytes) return "-";

  var k = 1024;
  var sizes = ["Bytes", "KB", "MB", "GB", "TB"];
  var i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
}

function updateBreadcrumb() {
  var parts = currentPath.split("/").filter(function (part) {
    return part;
  });
  var breadcrumb = $("#breadcrumb");
  breadcrumb.empty();
  breadcrumb.append('<a href="#" class="root">根目录</a>');
  breadcrumb.append('<span class="seperator"></span>');
  var len = parts.length;
  parts.forEach(function (part, index) {
    var path = parts.slice(0, index + 1).join("/");
    part = decodeURIComponent(part);
    // 如果是最后一个部分，不添加链接
    if (index === len - 1) {
      breadcrumb.append('<span class="current">' + part + "</span>");
      breadcrumb.append('<span class="seperator"></span>');
      return;
    }
    breadcrumb.append('<a href="#' + path + '">' + part + "</a>");
    breadcrumb.append('<span class="seperator"></span>');
  });
  if (currentPath) {
    uploadForm.show();
  } else {
    uploadForm.hide();
  }
}

$("#query").on("keydown", function (event) {
  if (event.keyCode === 13) {
    searchFiles();
  }
});

function renderMeta(item) {
  var time = new Date(item.modified_time).toLocaleString();
  if (item.type === "file") {
    var size = formatFileSize(item.size);
    return (
      '<span class="meta"><span class="size">' +
      size +
      '</span><span class="time">' +
      time +
      "</span></span>"
    );
  } else {
    return '<span class="meta"><span class="time">' + time + "</span></span>";
  }
}

function getDownloadPath(item, preview) {
  return "/download/" + item.path + (preview ? "?preview=true" : "");
}

// 添加文本文件预览功能
function onFileClick(e, item) {
  if (previewText(item)) {
  } else if (previewPdf(item)) {
  } else if (previewImage(item)) {
  } else {
    return;
  }

  $("#preview-filename").text(item.name);
  $("#btn-preview-download").attr("href", getDownloadPath(item));

  e.preventDefault();
  return false;
}

function previewText(item) {
  var textExtensions = [
    "txt",
    "md",
    "log",
    "ini",
    "conf",
    "config",
    "properties",
    "yaml",
    "json",
    "xml",
    "html",
    "htm",
    "css",
    "js",
    "py",
    "java",
    "c",
    "cpp",
    "h",
    "hpp",
    "cs",
    "php",
    "rb",
    "go",
  ];
  var ext = item.name.split(".").pop().toLowerCase();
  if (textExtensions.indexOf(ext) === -1) {
    return false;
  }

  $.get(getDownloadPath(item, true), function (data) {
    var modal = $("#preview-dialog");
    const textarea = $("<textarea readonly></textarea>");
    textarea.text(data);
    $("#preview-container").empty().append(textarea);
    modal.css("display", "flex");
    modal.focus();
  });
  return true;
}

function previewPdf(item) {
  var textExtensions = ["pdf"];
  var ext = item.name.split(".").pop().toLowerCase();
  if (textExtensions.indexOf(ext) === -1) {
    return false;
  }

  var modal = $("#preview-dialog");
  var iframe = $("<iframe>");
  iframe.addClass("preview-container preview-pdf");
  iframe.attr("src", getDownloadPath(item, true));
  iframe.attr("frameborder", "0");
  iframe.attr("allowfullscreen", "true");
  $("#preview-container").empty().append(iframe);
  modal.css("display", "flex");
  modal.focus();

  return true;
}

function previewImage(item) {
  var textExtensions = [
    "png",
    "jpg",
    "jpeg",
    "gif",
    "bmp",
    "webp",
    "tiff",
    "svg",
  ];
  var ext = item.name.split(".").pop().toLowerCase();
  if (textExtensions.indexOf(ext) === -1) {
    return false;
  }

  var modal = $("#preview-dialog");
  var img = $("<img>");
  img.addClass("preview-container preview-image");
  img.attr("src", getDownloadPath(item, true));
  img.attr("alt", item.name);
  img.attr("style", "max-width: 100%; max-height: 100%;");

  var imgContainer = $("<div>");
  imgContainer.addClass("preview-image-container");
  imgContainer.append(img);

  $("#preview-container").empty().append(imgContainer);
  modal.css("display", "flex");
  modal.focus();

  return true;
}

$("#preview-dialog").on("keydown", function (e) {
  if (e.keyCode === 27) {
    // ESC 键的键码
    $(this).hide();
  }
});

$("#btn-preview-close").on("click", function () {
  var modal = $("#preview-dialog");
  modal.css("display", "none");
});

// 工具函数：根据文件类型添加列表项到 ul 元素
function appendListItem(ul, item, text, forSearch) {
  var meta = renderMeta(item);
  var li = $("<li>");
  var container = $('<div class="name-container">');
  if (item.type === "file") {
    li.addClass("is-file");
  } else {
    li.addClass("is-dir");
  }
  if (forSearch) {
    var pathList = [];
    var allPath = item.path.split("/");
    allPath.forEach(function (part, idx) {
      pathList.push(part);
      var itemPath = pathList.join("/");
      if (idx < allPath.length - 1) {
        container.append(
          '<a href="#' + itemPath + '" class="part">' + part + "</a>"
        );
        container.append('<span class="seperator">/</span>');
      } else {
        var a = $(
          '<a href="' +
            (item.type === "file" ? "/download/" : "#") +
            item.path +
            '"></a>'
        );
        a.html(text);
        if (item.type === "file") {
          a.on("click", function (e) {
            onFileClick(e, item);
          });
        }
        container.append(a);
      }
    });
  } else {
    var a = $(
      '<a href="' +
        (item.type === "file" ? "/download/" : "#") +
        item.path +
        '">' +
        text +
        "</a>"
    );
    if (item.type === "file") {
      a.on("click", function (e) {
        onFileClick(e, item);
      });
    }
    container.append(a);
  }
  li.append(container);
  li.append(meta);
  ul.append(li);
}

$("#btn-preview-fullscreen").click(function () {
  var dialog = $("#preview-dialog");
  if (dialog.hasClass("fullscreen")) {
    dialog.removeClass("fullscreen");
    $(this).text("全屏");
  } else {
    dialog.addClass("fullscreen");
    $(this).text("退出全屏");
  }
});
